<template>
	<view class="content">
		<view>请问请问</view>
		<button type="default" size="mini" @click="editItem()">新增</button>
		<uni-list>
			<uni-list-item v-for="item in items" :key="item.id" :clickable="true"
				:title="item.id+ '-----'+item.name + '-----'+ item.age " @click="detail(item.id)"></uni-list-item>
		</uni-list>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				items: [],
				pageNum: 1,
				pageSize: 10
			}
		},

		onShow() {
			this.pageNum = 1
			this.loadData()
		},
		methods: {
			//数据加载
			loadData() {
				let that = this
				uni.request({
					url: `http://localhost:9000/uniapp/student/list?pageNum=${that.pageNum}&pageSize=${that.pageSize}`,
					method: 'GET',
					success: (res) => {
						that.items = res.data
						uni.stopPullDownRefresh();
					},
					fail: (err) => {
						uni.stopPullDownRefresh();
						console.error(err)
					}
				});
			},

			//点击列表某一条
			detail(id) {
				// console.log(id)
				let that = this
				uni.showActionSheet({
					itemList: ['修改', '删除'],
					itemColor: '#58AFEF',
					success: function(res) {
						// 修改
						if (res.tapIndex === 0) {
							uni.navigateTo({
								url: `/pages/edit/edit?id=${id}`
							})
						}
						//删除
						if (res.tapIndex === 1) {
							that.delItem(id)
						}
					},
					fail: function(res) {
						console.log(res);
					}
				})
			},

			//新增or编辑
			editItem(id) {
				// console.log(id)
				//判断新增or修改
				if (id) {
					uni.navigateTo({
						url: `/pages/edit/edit?id=${id}`
					})
				} else {
					uni.navigateTo({
						url: `/pages/edit/edit`
					})
				}


			},
			//删除
			delItem(id) {
				let that = this
				uni.showModal({
					title: '删除',
					content: '确定要删除此条记录吗？',
					success: function(res) {
						if (res.confirm) {
							uni.request({
								url: `http://localhost:9000/uniapp/student/${id}`,
								method: 'DELETE',
								success: (res) => {
									console.log(res.data)
									if (res.data) {
										that.pageNum = 1
										that.loadData()
									}
								},
								fail: (err) => {
									console.error(err)
								}
							});

						} else if (res.cancel) {
							console.log('cancel')
						}
					}
				});
			},
		},
		//下拉刷新
		onPullDownRefresh() {
			this.loadData()
		},
		//上拉加载
		onReachBottom() {
			console.log('bootom')
			let that = this
			that.pageNum++
			uni.request({
				url: `http://localhost:9000/uniapp/student/list?pageNum=${that.pageNum}&pageSize=${that.pageSize}`,
				method: 'GET',
				success: (res) => {
					if (res.data.length == 0) {
						that.pageNum--
						console.log('end')
						uni.showToast({
						    title: '无更多内容',
						    duration: 2000
						});
						return
					}
					uni.stopPullDownRefresh();
					that.items = [...that.items, ...res.data]

				},
				fail: (err) => {
					uni.stopPullDownRefresh();
					console.error(err)
				}
			});
		}
	}
</script>
<style>

</style>
